import 'dart:convert';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:intl/intl.dart';
import 'package:path/path.dart';
import 'package:flutter_syt/application.dart';
import 'package:flutter_syt/datas/provider_index_setting.dart';
import 'package:flutter_syt/domain/mine/service/provider_unread_msg.dart';
import 'package:flutter_syt/domain/widgets/crop_image_route.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/global_easy_loading.dart';
import 'package:flutter_syt/routes.all.dart';
import 'package:flutter_syt/theme/theme_color.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/utils/permission_helper.dart';
import 'package:url_launcher/url_launcher_string.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

// import 'package:wechat_camera_picker/wechat_camera_picker.dart';
import 'package:yyy_route_annotation/yyy_route_annotation.dart';

class DialogHelper {
  static showBottom(BuildContext context) async {
    var item = [
      S.of(context).take_a_photo,
      S.of(context).choose_from_album,
      S.of(context).cancel
    ];
    return showModalBottomSheet(
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
        topLeft: Radius.circular(8),
        topRight: Radius.circular(8),
      )),
      isScrollControlled: true,
      context: context,
      builder: (BuildContext context) {
        return ListView.separated(
          separatorBuilder: (context, index) {
            return Divider(
              height: 1,
              color: ThemeColor.colorBlack40,
            );
          },
          shrinkWrap: true,
          itemCount: item.length,
          itemBuilder: (BuildContext context, int index) {
            return ListTile(
                title: Center(
                  child: Text(
                    item[index],
                    style: TextStyle(
                      fontSize: 14,
                      color: index == item.length - 1
                          ? ThemeColor.colorBlack80
                          : ThemeColor.colorBlack60,
                    ),
                  ),
                ),
                onTap: ClickUtils.debounce(
                  () async {
                    if (index == 0) {
                      if (await PermissionHelper.checkCameraPermission(
                          context)) {
                        Navigator.pop(context, index);
                      }
                    } else if (index == 1) {
                      if (await PermissionHelper.checkPhotosPermission(
                          context)) {
                        Navigator.pop(context, index);
                      }
                    } else {
                      Navigator.pop(context, index);
                    }
                  },
                ));
          },
        );
      },
    );
  }

  static showFeedbackBottom(
    BuildContext context,
    List modules,
    // Function(Map data) clickModule,
    {
    String? title,
  }) async {
    var item = [];

    item.addAll(modules.map((e) => e['title']).toList());
    item.add(S.current.cancel);
    return showModalBottomSheet(
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
        topLeft: Radius.circular(8),
        topRight: Radius.circular(8),
      )),
      isScrollControlled: true,
      context: context,
      builder: (BuildContext context) {
        return Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Visibility(
                visible: title != null,
                child:
                    // title
                    Container(
                  height: 50,
                  alignment: Alignment.centerLeft,
                  margin: EdgeInsets.symmetric(horizontal: 15),
                  child: Text(
                    title ?? '',
                    style: TextStyle(
                        fontSize: 16,
                        color: ThemeColor.colorBlack80,
                        fontWeight: FontWeight.w500),
                  ),
                )),
            // item.length > 4
            //     ? SizedBox(
            //         height: 200,
            //         child: GridView.count(
            //           // 创建几列
            //           crossAxisCount: 2,
            //           // Axis.horizontal表示横向滑动，scrollDirection: Axis.vertical表示纵向滑动
            //           scrollDirection: Axis.vertical,
            //           // 列之间的间距
            //           // crossAxisSpacing: ,
            //           // 行之间的间距
            //           // mainAxisSpacing: ,
            //           // 默认false 是否根据子孩子的宽高自动包裹item自身
            //           shrinkWrap: false,
            //           // true表示数据倒序排列 false表示顺序排列
            //           reverse: false,
            //           // 子孩子的比例
            //           childAspectRatio: 4,
            //           // 设置子孩子item,这里传入子孩子控件
            //           children: item.map((e) {
            //             return Text(
            //               e,
            //               textAlign: TextAlign.center,
            //               style: TextStyle(
            //                 fontSize: 16,
            //                 color: ThemeColor.colorBlack60,
            //               ),
            //             );
            //           }).toList(),
            //         ),
            //       )
            // :
            Container(
              constraints: BoxConstraints(maxHeight: 400.w),
              // height: 400.w,
              child: ListView.separated(
                separatorBuilder: (context, index) {
                  return Divider(
                    height: 1,
                    color: ThemeColor.colorBlack40,
                  );
                },
                shrinkWrap: true,
                itemCount: item.length,
                itemBuilder: (BuildContext context, int index) {
                  return ListTile(
                      title: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            item[index],
                            style: TextStyle(
                              fontSize: 16,
                              color: ThemeColor.colorBlack60,
                            ),
                          ),
                        ],
                      ),
                      onTap: ClickUtils.debounce(
                        () async {
                          //  clickModule(map)

                          Navigator.pop(
                              context,
                              (item.length - 1) > index
                                  ? modules[index]
                                  : null);
                          //  Navigator.pop(context,);
                          // Future.delayed(Duration.zero, () {
                          //    if ((item.length - 1) > index) {
                          //   clickModule(modules[index]);
                          //   //  Navigator.pop(context, index);
                          // }

                          // });

                          // }
                        },
                      ));
                },
              ),
            )
          ],
        );
      },
    );
  }

// [{key: customer_hotline, value: 028-67563733}, {key: reserve_hotline, value: 021-33192277}, {key: hotline_copywriting, value: {"zh":"客服热线","en":"Hotline"}}, {key: email_copywriting, value: {"zh":"邮箱反馈","en":"E-mail"}}, {key: email_feedback, value: officialappservice@2021chengdu.com}, {key: reserve_copywriting, value: {"zh":"备用客服热线","en":"Alternate Hotline"}}, {key: online_copywriting, value: {"zh":"在线客服","en":"Online"}}]
  static String? getValueForKey(List items, String key) {
    String? value;
    items.forEach((element) {
      if (element['key'] == key) {
        value = element['value'];
      }
    });
    return value;
  }

  static showServiceBottom(BuildContext context, List sysTemBatch,
      ProviderIndexSetting provider, ProviderUnReadMsg unReadMsg) async {
    var local =
        appContext.storage.getString("storyLocal") ?? Intl.getCurrentLocale();
    var item = [
      // S.of(context).take_a_photo,
      // S.of(context).choose_from_album,
      // S.of(context).cancel
    ];

//邮箱反馈
    if (provider.indexSetting.emailFeedback == 1) {
      dynamic value =
          jsonDecode(getValueForKey(sysTemBatch, 'email_copywriting') ?? '{}');
      if (value is Map && value.keys.toList().isNotEmpty) {
        item.add({
          // assets/icons/icon_email_feedback.png
          'im': 'assets/icons/icon_email_feedback.png',
          'tit': local.contains('zh') ? value['zh'] : value['en']
        });
      }
    }

    //客服热线
    if (provider.indexSetting.customerHotline == 1) {
      dynamic value = jsonDecode(
          getValueForKey(sysTemBatch, 'hotline_copywriting') ?? '{}');
      if (value is Map && value.keys.toList().isNotEmpty) {
        item.add({
          'im': 'assets/icons/icon_reserve_hotline.png',
          'tit': local.contains('zh') ? value['zh'] : value['en']
        });
      }
      //备用客服热线
    }
    if (provider.indexSetting.reserveCustomerHotline == 1) {
      dynamic value = jsonDecode(
          getValueForKey(sysTemBatch, 'reserve_copywriting') ?? '{}');
      if (value is Map && value.keys.toList().isNotEmpty) {
        item.add({
          'im': 'assets/icons/icon_online_service_op.png',
          'tit': local.contains('zh') ? value['zh'] : value['en']
        });
      }
      //在线客服
    }
    if (provider.indexSetting.service == 1) {
      dynamic value =
          jsonDecode(getValueForKey(sysTemBatch, 'online_copywriting') ?? '{}');
      if (value is Map && value.keys.toList().isNotEmpty) {
        item.add({
          'im': 'assets/icons/icon_online_service.png',
          'tit': local.contains('zh') ? value['zh'] : value['en']
        });
      }
    }
    item.add({'im': '', 'tit': S.current.cancel});
    return showModalBottomSheet(
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
        topLeft: Radius.circular(8),
        topRight: Radius.circular(8),
      )),
      isScrollControlled: true,
      context: context,
      builder: (BuildContext context) {
        return ListView.separated(
          separatorBuilder: (context, index) {
            return Divider(
              height: 1,
              color: ThemeColor.colorBlack40,
            );
          },
          shrinkWrap: true,
          itemCount: item.length,
          itemBuilder: (BuildContext context, int index) {
            Map map = item[index];

            return ListTile(
                title: map['im'].length == 0
                    ? Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            map['tit'],
                            style: TextStyle(
                              fontSize: 16,
                              color: ThemeColor.colorBlack60,
                            ),
                          ),
                        ],
                      )
                    : Row(
                        children: [
                          SizedBox(
                              width: 24,
                              height: 24,
                              child: Stack(
                                children: [
                                  Image.asset(
                                    map['im'],
                                    width: 20,
                                  ),
                                  Positioned(
                                      top: 0,
                                      right: 0,
                                      child: Visibility(
                                          visible: unReadMsg.unReadNum > 0 &&
                                              map['im'] ==
                                                  'assets/icons/icon_online_service.png',
                                          child: Container(
                                              width: 4,
                                              height: 4,
                                              decoration: BoxDecoration(
                                                  color: Color(0xffEA2121),
                                                  borderRadius:
                                                      BorderRadius.circular(
                                                          2)))))
                                ],
                              )),
                          SizedBox(
                            width: 16,
                          ),
                          Text(
                            map['tit'],
                            style: TextStyle(
                              fontSize: 14,
                              color: index == item.length - 1
                                  ? ThemeColor.colorBlack80
                                  : ThemeColor.colorBlack60,
                            ),
                          ),
                        ],
                      ),
                onTap: ClickUtils.debounce(
                  () async {
                    // ''.contains('icon_email_feedback')
                    if (map['im'].contains('icon_email_feedback')) {
                      dynamic value =
                          getValueForKey(sysTemBatch, 'email_feedback');
                      launchUrlString("mailto:$value");
                    } else if (map['im'].contains('icon_reserve_hotline')) {
                      dynamic value =
                          getValueForKey(sysTemBatch, 'customer_hotline');
                      launchUrlString("tel:$value");
                    } else if (map['im'].contains('icon_online_service_op')) {
                      dynamic value =
                          getValueForKey(sysTemBatch, 'reserve_hotline');
                      launchUrlString("tel:$value");
                    } else if (map['im'].contains('icon_online_service')) {
                      RouteManager.push(
                          context, RoutMapping.service_socket('self'));
                    }

                    // if (index == 0) {
                    //   if (await PermissionHelper.checkCameraPermission(
                    //       context)) {
                    //     Navigator.pop(context, index);
                    //   }
                    // } else if (index == 1) {
                    //   if (await PermissionHelper.checkPhotosPermission(
                    //       context)) {
                    //     Navigator.pop(context, index);
                    //   }
                    // } else {
                    Navigator.pop(context, index);
                    // }
                  },
                ));
          },
        );
      },
    );
  }
}

class ImageHelper {
  static Map<String, CompressFormat> _suffixMap = {
    'jpg': CompressFormat.jpeg,
    'png': CompressFormat.png,
    'heic': CompressFormat.heic,
    'webp': CompressFormat.webp
  };

  static Future<File> cropImage(BuildContext context, String path) async {
    return await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => CropImageRoute(File(path)),
      ),
    );
  }

  /// source: 0 camera， 1 gallery
  static Future<File?> pickSingleImage(BuildContext context,
      {int source = 0, bool needCompress = true}) async {
    await Future.delayed(Duration(milliseconds: 500));
    var originFile;
    // if (0 == source && await PermissionHelper.checkCameraPermission(context)) {
    //   //暂时注释
    //   var assetEntity = await CameraPicker.pickFromCamera(context);
    //   originFile = await assetEntity!.originFile;
    // } else source == 1 &&
    if (await PermissionHelper.checkPhotosPermission(context)) {
      var assetEntity = await AssetPicker.pickAssets(context,
          pickerConfig:
              AssetPickerConfig(maxAssets: 1, requestType: RequestType.image));
      originFile = await assetEntity!.first.file;
    }

    // 压缩
    if (originFile == null) {
      return Future.value(null);
    }

    if (needCompress) {
      return await _compressImage(originFile);
    }
    return originFile;
  }

  /// source: 0 camera， 1 gallery
  // static pickSingleVideo(BuildContext context, {int source = 0}) async {
  //   await Future.delayed(Duration(milliseconds: 500));
  //   var file;
  //   if (0 == source && await PermissionHelper.checkCameraPermission(context)) {
  //     //暂时注释
  //     var assetEntity = await CameraPicker.pickFromCamera(context);
  //     file = assetEntity?.file
  //         .timeout(Duration(seconds: 5), onTimeout: () => null);
  //   } else if (source == 1 &&
  //       await PermissionHelper.checkCameraPermission(context)) {
  //     // var assetEntity = await AssetPicker.pickAssets(
  //     //   context,
  //     //   maxAssets: 1,
  //     //   requestType: RequestType.video,
  //     // );
  //     var assetEntity = await AssetPicker.pickAssets(context,
  //         pickerConfig:
  //             AssetPickerConfig(maxAssets: 1, requestType: RequestType.video));
  //     file = assetEntity?.first.file
  //         .timeout(Duration(seconds: 5), onTimeout: () => null);
  //   }
  //
  //   return file;
  // }

  /// source: 0 camera， 1 gallery
  static Future<ChooseImageData> pickMutableImage(BuildContext context,
      {int source = 0,
      bool needCompress = true,
      int maxCount = 1,
      List<AssetEntity>? selected}) async {
    await Future.delayed(Duration(milliseconds: 500));
    List<File> originFile = [];
    List<AssetEntity> validEntities = [];

    if (await PermissionHelper.checkPhotosPermission(context)) {
      var assetEntity = await AssetPicker.pickAssets(context,
              pickerConfig: AssetPickerConfig(
                  maxAssets: maxCount,
                  requestType: RequestType.image,
                  selectedAssets: selected)) ??
          [];

      for (var item in assetEntity) {
        var file = await item.file;
        if (file != null) {
          String formatStr = file.path.split('.').last.toLowerCase();
          if (formatStr.contains('png') ||
              formatStr.contains('jpg') ||
              formatStr.contains('jpeg') ||
              formatStr.contains('webp')) {
            var realFile = await _compressImage(file);
            if (realFile != null) {
              originFile.add(realFile);
              validEntities.add(item); // 只添加有效的实体
            }
          } else {
            customShowToast(S().main_fileerrortips);
          }
        }
      }
    }

    return ChooseImageData(originFile, entities: validEntities);
  }

  static Future<File> _compressImage(File originFile) async {
    var directory = Directory(originFile.path);
    var baseName = basename(originFile.path);
    var targetPath = join(directory.parent.path, 'compressed_$baseName');

    try {
      XFile? compressedImageFile =
          await FlutterImageCompress.compressAndGetFile(
              originFile.path, targetPath,
              // format: CompressFormat.png
              format: _compressFormat(originFile.path));
      print('compressed image file path is --> ${compressedImageFile?.path}');
      if (compressedImageFile != null) {
        // .existsSync();
        return File(compressedImageFile.path);
      }

      return originFile;
    } catch (e) {
      return originFile;
      // print('${e}');
    }
  }

  static Future<File?> compressImage(File originFile) async {
    return _compressImage(originFile);
  }

  static _compressFormat(String path) {
    var lowerPath = path.toLowerCase();
    for (var each in _suffixMap.keys) {
      var res = lowerPath.endsWith(each);
      if (res) {
        return _suffixMap[each];
      }
    }

    throw Error.safeToString('Can not support file type, fil is $path');
  }

  /// source: 0 camera， 1 gallery
// static Future<ChooseImageData> pickImageAndVideo(
//   BuildContext context, {
//   int maxCount = 1,
//   int source = 0,
// }) async {
//   await Future.delayed(Duration(milliseconds: 500));
//   List<File> originFile = [];
//   List<AssetEntity>? entyties;
//   if (0 == source &&
//       await PermissionHelper.checkCameraPermission(context)) {
//     var assetEntity = await CameraPicker.pickFromCamera(
//       context,
//       pickerConfig: CameraPickerConfig(
//         enableRecording: true,
//         resolutionPreset: ResolutionPreset.medium,
//         maximumRecordingDuration: const Duration(seconds: 10),
//       ),
//     );
//
//     if (assetEntity != null) {
//       entyties = [assetEntity];
//       var file = await assetEntity.file;
//       // assetEntity.thumbData
//       if (assetEntity.type == AssetType.image) {
//         if (file != null) {
//           var realFile = await _compressImage(file);
//           if (realFile != null) {
//             originFile.add(realFile);
//           }
//         }
//       } else if (assetEntity.type == AssetType.video) {
//         if (file != null) {
//           originFile.add(file);
//         }
//       }
//       return ChooseImageData(originFile, entities: entyties);
//     } else {
//       return ChooseImageData([], entities: []);
//     }
//   } else if (await PermissionHelper.checkPhotosPermission(context) &&
//       source == 1) {
//     var assetEntity = await AssetPicker.pickAssets(context,
//             pickerConfig: AssetPickerConfig(
//                 maxAssets: maxCount,
//                 requestType: RequestType.common,
//                 filterOptions: FilterOptionGroup(
//                     videoOption: FilterOption(
//                         durationConstraint: DurationConstraint(
//                             min: Duration(seconds: 3),
//                             max: Duration(seconds: 10)))))) ??
//         [];
//     entyties = assetEntity;
//     for (var item in assetEntity) {
//       var file = await item.file;
//       if (item.type == AssetType.image) {
//         if (file != null) {
//           var realFile = await _compressImage(file);
//           if (realFile != null) {
//             originFile.add(realFile);
//           }
//         }
//       } else if (item.type == AssetType.video) {
//         if (file != null) {
//           originFile.add(file);
//         }
//       }
//     }
//   }
//   return ChooseImageData(originFile, entities: entyties);
// }
}

class ChooseImageData {
  List<File> files;
  List<AssetEntity>? entities;

  ChooseImageData(this.files, {this.entities});
}
